// src/App.tsx

import React, { useState, useEffect } from "react";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-draw/dist/leaflet.draw.css";
import "leaflet-draw"; // 导入 Leaflet.draw 插件

// 导入自定义组件
import LeftSidebar from "./components/LeftSidebar";
import RightSidebar from "./components/RightSidebar";
import MissionTypeModal from "./components/MissionTypeModal";
import MapComponent from "./components/MapComponent"; // 封装地图逻辑
import {
  CAMERA_SENSOR_WIDTH,
  CAMERA_SENSOR_HEIGHT,
  CAMERA_FOCAL_LENGTH,
  CAMERA_IMAGE_WIDTH_PIXELS,
  CAMERA_IMAGE_HEIGHT_PIXELS,
  AIRPORT_COORDS, // 导入 AIRPORT_COORDS
} from "./components/utils";

import type { CameraParams } from "./components/utils";

// 定义任务类型 - 确保这一行有 'export'
export type MissionType = "mapping" | "oblique" | null;

// 定义调试数据接口
export interface DebugData {
  rotatedPolygonForScan: Feature<Polygon> | null;
  bufferedPolygonForScan: Feature<Polygon> | null;
  scanLines: Feature<LineString>[];
  midPoints: Feature<Point>[];
  midPointsInPolygon: Feature<Point>[]; // 那些被判断为在多边形内部的中点
}

function App() {
  const [isMissionModalOpen, setIsMissionModalOpen] = useState(false);
  const [isRightSidebarOpen, setIsRightSidebarOpen] = useState(false);
  const [currentMissionType, setCurrentMissionType] =
    useState<MissionType>(null);
  const [drawnPolygon, setDrawnPolygon] = useState<L.Polygon | null>(null); // 存储绘制的多边形
  const [flightPathLayer, setFlightPathLayer] = useState<L.FeatureGroup | null>(
    null
  ); // 存储生成的航线图层
  const [isDrawingEnabled, setIsDrawingEnabled] = useState(false); // <-- 新增状态，控制绘制工具
  const [debugData, setDebugData] = useState<DebugData | null>(null); // <-- 新增调试数据状态
  const [calculatedAutoAngle, setCalculatedAutoAngle] = useState<number | null>(
    null
  ); // 新增状态：自动计算的航线角度
  const [showDebugLayers, setShowDebugLayers] = useState(false); // 新增状态：控制调试图层显示

  // 新增：起飞点状态
  const [takeoffPoint, setTakeoffPoint] = useState<L.LatLng>(
    new L.LatLng(AIRPORT_COORDS[0], AIRPORT_COORDS[1])
  );
  // 新增：设置起飞点模式
  const [isSettingTakeoffPoint, setIsSettingTakeoffPoint] = useState(false);

  // 示例相机参数 (从 utils.ts 导入)
  const CAMERA_PARAMS: CameraParams = {
    SENSOR_WIDTH: CAMERA_SENSOR_WIDTH,
    SENSOR_HEIGHT: CAMERA_SENSOR_HEIGHT,
    FOCAL_LENGTH: CAMERA_FOCAL_LENGTH,
    IMAGE_WIDTH_PIXELS: CAMERA_IMAGE_WIDTH_PIXELS,
    IMAGE_HEIGHT_PIXELS: CAMERA_IMAGE_HEIGHT_PIXELS,
  };

  const handleNewTaskClick = () => {
    setIsMissionModalOpen(true);
  };

  const handleMissionTypeSelect = (type: MissionType) => {
    setCurrentMissionType(type);
    setIsMissionModalOpen(false);
    setIsRightSidebarOpen(true);
    setIsDrawingEnabled(true);
    setDrawnPolygon(null); // 确保这里清空
    if (flightPathLayer) {
      flightPathLayer.clearLayers();
    }
    setFlightPathLayer(null);
    setDebugData(null); // <-- 清空调试数据
    setCalculatedAutoAngle(null); // 清空自动计算角度
    setShowDebugLayers(false); // 新建任务时默认关闭调试图层
    setTakeoffPoint(new L.LatLng(AIRPORT_COORDS[0], AIRPORT_COORDS[1])); // 新建任务时清空起飞点
    setIsSettingTakeoffPoint(false); // 关闭起飞点设置模式
    console.log("任务类型选择，isDrawingEnabled:", true, "drawnPolygon:", null); // <-- 添加日志
  };

  const handleCloseRightSidebar = () => {
    setIsRightSidebarOpen(false);
    setCurrentMissionType(null);
    setIsDrawingEnabled(false);
    setDrawnPolygon(null); // 确保这里清空
    if (flightPathLayer) {
      flightPathLayer.clearLayers();
    }
    setFlightPathLayer(null);
    setDebugData(null); // <-- 清空调试数据
    setCalculatedAutoAngle(null); // 清空自动计算角度
    setShowDebugLayers(false); // 关闭侧边栏时关闭调试图层
    setTakeoffPoint(new L.LatLng(AIRPORT_COORDS[0], AIRPORT_COORDS[1])); // 关闭侧边栏时清空起飞点
    setIsSettingTakeoffPoint(false); // 关闭起飞点设置模式
    console.log("关闭侧边栏，isDrawingEnabled:", false, "drawnPolygon:", null); // <-- 添加日志
  };

  // 地图绘制完成事件处理
  const handlePolygonCreated = (layer: L.Polygon) => {
    setDrawnPolygon(layer);
    setIsRightSidebarOpen(true);
    setIsDrawingEnabled(false); // 绘制完成后禁用绘制工具
    if (flightPathLayer) {
      flightPathLayer.clearLayers();
      setFlightPathLayer(null);
    }
    setDebugData(null); // <-- 清空调试数据
    setCalculatedAutoAngle(null); // 清空自动计算角度，等待重新计算
    setIsSettingTakeoffPoint(false); // 绘制多边形后关闭起飞点设置模式
    console.log(
      "App: 多边形创建回调，设置 drawnPolygon:",
      layer,
      "isDrawingEnabled:",
      false
    ); // <-- 添加日志
  };

  // 地图绘制编辑事件处理 (保持不变)
  const handlePolygonEdited = (layer: L.Polygon) => {
    setDrawnPolygon(layer);
    console.log("Polygon edited, re-calculating route...");
    if (flightPathLayer) {
      flightPathLayer.clearLayers();
      setFlightPathLayer(null);
      setDebugData(null); // <-- 清空调试数据
    }
    setCalculatedAutoAngle(null); // 清空自动计算角度，等待重新计算
    setIsSettingTakeoffPoint(false); // 编辑多边形后关闭起飞点设置模式
  };

  // 地图绘制删除事件处理
  const handlePolygonDeleted = () => {
    setDrawnPolygon(null); // 确保这里清空
    if (flightPathLayer) {
      flightPathLayer.clearLayers();
    }
    setFlightPathLayer(null);
    setIsDrawingEnabled(true); // 删除后重新激活绘制工具
    setDebugData(null); // <-- 清空调试数据
    setCalculatedAutoAngle(null); // 清空自动计算角度
    setShowDebugLayers(false); // 删除多边形后关闭调试图层
    setTakeoffPoint(new L.LatLng(AIRPORT_COORDS[0], AIRPORT_COORDS[1])); // 删除多边形后清空起飞点
    setIsSettingTakeoffPoint(false); // 关闭起飞点设置模式
    console.log(
      "App: 多边形删除回调，设置 drawnPolygon:",
      null,
      "isDrawingEnabled:",
      true
    ); // <-- 添加日志
  };

  // 航线计算完成后，更新 flightPathLayer
  const handleRouteCalculated = (
    newFlightPath: L.FeatureGroup,
    debugInfo: DebugData | null,
    autoAngle?: number // 接收自动计算的角度
  ) => {
    setFlightPathLayer(newFlightPath);
    setDebugData(debugInfo); // <-- 更新调试数据
    if (autoAngle !== undefined) {
      setCalculatedAutoAngle(autoAngle); // 更新自动计算角度
    }
  };

  // 切换设置起飞点模式
  const handleSetTakeoffPointMode = (enabled: boolean) => {
    setIsSettingTakeoffPoint(enabled);
    if (enabled) {
      // 如果开启设置起飞点模式，则禁用多边形绘制
      setIsDrawingEnabled(false);
      // 清除任何临时绘制的多边形
      // MapComponent 内部会处理 tempPolygonRef 的清除
    } else {
      // 如果关闭设置起飞点模式，且没有已绘制多边形，则重新启用多边形绘制
      if (!drawnPolygon) {
        setIsDrawingEnabled(true);
      }
    }
  };

  return (
    <div className="flex h-screen w-screen bg-[#1a1a1a] text-[#e0e0e0]">
      <LeftSidebar
        onNewTaskClick={handleNewTaskClick}
        currentMissionType={currentMissionType} // 传递当前任务类型
        drawnPolygon={drawnPolygon} // 传递已绘制多边形
        isSettingTakeoffPoint={isSettingTakeoffPoint} // 传递起飞点设置模式
        onSetTakeoffPointMode={handleSetTakeoffPointMode} // 传递切换起飞点设置模式的函数
        takeoffPoint={takeoffPoint} // 传递起飞点状态
      />

      <MapComponent
        key="main-map-component" // <--- 关键修改：添加一个稳定的 key
        drawnPolygon={drawnPolygon}
        setDrawnPolygon={setDrawnPolygon}
        onPolygonCreated={handlePolygonCreated}
        onPolygonEdited={handlePolygonEdited}
        onPolygonDeleted={handlePolygonDeleted}
        flightPathLayer={flightPathLayer}
        setFlightPathLayer={setFlightPathLayer}
        isDrawingEnabled={isDrawingEnabled}
        debugData={debugData} // <-- 传递调试数据
        showDebugLayers={showDebugLayers} // 传递调试图层显示状态
        takeoffPoint={takeoffPoint} // 新增：传递起飞点
        setTakeoffPoint={setTakeoffPoint} // 新增：传递设置起飞点函数
        isSettingTakeoffPoint={isSettingTakeoffPoint} // 新增：传递起飞点设置模式
        onSetTakeoffPointMode={handleSetTakeoffPointMode} // 新增：传递切换起飞点设置模式的函数
      />

      <RightSidebar
        isOpen={isRightSidebarOpen}
        onClose={handleCloseRightSidebar}
        missionType={currentMissionType}
        drawnPolygon={drawnPolygon} // 确保传递给 RightSidebar
        cameraParams={CAMERA_PARAMS}
        onRouteCalculated={handleRouteCalculated}
        flightPathLayer={flightPathLayer}
        calculatedAutoAngle={calculatedAutoAngle} // 传递自动计算角度
        showDebugLayers={showDebugLayers} // 传递调试图层显示状态
        onToggleDebugLayers={() => setShowDebugLayers(!showDebugLayers)} // 传递切换调试图层函数
        takeoffPoint={takeoffPoint} // 新增：传递起飞点
      />

      <MissionTypeModal
        isOpen={isMissionModalOpen}
        onClose={() => setIsMissionModalOpen(false)}
        onSelect={handleMissionTypeSelect}
      />
    </div>
  );
}

export default App;
